package demo.helloworld.util;

import org.osgl.util.S;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by vilen on 2017/3/2.
 */
public class Tool {
    public static String hex(byte[] array) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i]
                    & 0xFF) | 0x100).substring(1,3));
        }
        return sb.toString();
    }
    public static String md5Hex (String message) {
        try {
            MessageDigest md =
                    MessageDigest.getInstance("MD5");
            return hex (md.digest(message.getBytes("CP1252")));
        } catch (NoSuchAlgorithmException e) {
        } catch (UnsupportedEncodingException e) {
        }
        return null;
    }

    public static String gravatar(String email) {
        String avatarUrl = "https://secure.gravatar.com/avatar";
        if (S.isBlank(email)) {
            return avatarUrl;
        }
        String hash = Tool.md5Hex(email.trim().toLowerCase());
        return avatarUrl + "/" + hash;
    }
}
